package com.bugreport.integration.web;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.junit.Test;

import com.bugreport.web.ReportIssueController;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.TextPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.util.NameValuePair;

public class ReportIssueTestCase extends JettyServerTestCase {

	private static final Logger logger = Logger.getLogger(ReportIssueTestCase.class);

	@Test
	public void reportIssueUsingMantis128() throws Exception {

		// Given
		final WebClient webClient = new WebClient();

		WebRequest request = new WebRequest(new URL(getJettyBaseUrl() + "services/reportIssue.do"), HttpMethod.POST);
		request.setRequestParameters(new ArrayList<NameValuePair>());
		request.getRequestParameters().add(new NameValuePair(ReportIssueController.PARAM_ISSUE_TITLE, "title"));
		request.getRequestParameters().add(
				new NameValuePair(ReportIssueController.PARAM_ISSUE_DESCRIPTION, "description"));
		request.getRequestParameters()
				.add(new NameValuePair(ReportIssueController.PARAM_ISSUE_PAGE_URL, "www.bar.foo"));
		request.getRequestParameters().add(
				new NameValuePair(ReportIssueController.PARAM_ISSUE_PAGE_PAGE_HTML_CONTENT, "content"));

		// When
		TextPage page = webClient.getPage(request);
		logger.debug(page.getContent());

		// Then
		assertNotNull(page);
		assertTrue(Pattern
				.compile("^.*<div>.{2}Your issue has been successfully reported under number #[0-9]+\\..{2}</div>$", Pattern.DOTALL)
				.matcher(page.getContent()).matches());
	}

	// FIXME add test to be sure we refuse GET requests
}
